<?php

class UserController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';
	
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
		);
	}
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array(
					'index',
					'view', 
					'registration', 
					'cofirmation', 
					'newpas', 
					'captcha', 
					'pl', 
					'mlr',
					'ajaxreg',
					'fk',
					'punished',
				),
				'users'=>array('*'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('profile', 'statistic', 'sendEmails', 'recommend'),
				'roles'=>array('user'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	/**
	 * Registration account
	 */
	public function actionRegistration() {
		
		$model = new User;
		$model->setScenario('registration');
		
		if(isset($_POST['User'])) {
			$model->attributes = $_POST['User'];
			if($model->validate()) {
				$model->password = md5($model->password);
				if($model->save(false)) {
					$model->checkToOwner();
					$model->sendConfirmation();
					Yii::app()->user->setFlash('success', 'Вы успешно зарегистрировались, на Ваш email было отправленно письмо с подтверждением регистрации');
				}
			}
		}
		
		$this->render('registration',array(
			'model'=>$model,
		));	
	}
	
	/**
	 * 
	 */
	public function actionAjaxreg() {
		$result = array();
		if(isset($_POST['User'])) {
			$model = new User;
			$model->setScenario('registration');
			$model->attributes = $_POST['User'];
			if($model->validate()) {
				$model->password = md5($model->password);
				if($model->save(false)) {
					$model->checkToOwner();
					$model->sendConfirmation();
					$result['success'] = 'Вы успешно зарегистрировались, на Ваш email было отправленно письмо с подтверждением регистрации';
				}
			} else {
				$result['form'] = $this->renderPartial('/user/_registration', array('model'=>$model), true, false);
			}
		}
		echo CJSON::encode($result);
		Yii::app()->end();		
	} 
	
	/**
	 * Confirmation email
	 */
	public function actionCofirmation() {
		if(isset($_GET['cl'])) {
			$cl = preg_replace("/[^0-9]/", '', $_GET['cl']);
			if($user = User::getByConfirmLink($cl)) {
				$user->role = 'user';
				$user->save(false);
				$user->login();
				
				Yii::app()->user->setFlash('success', 'Email успешно дотвержден!');
				$this->redirect('/user/profile');
			} 
		}
		$this->redirect('/');
	}
	
	/**
	 * 
	 */
	public function actionProfile() {
		$model = Yii::app()->user->getModel();
		$model->setScenario('profile');
		
		$oldPass = $model->password;
		$model->password = '';
				
		if(isset($_POST['User']))
		{
			$newPas = true;
			
			$model->attributes=$_POST['User'];
			if($model->password == '') {
				$model->_password2 = $model->password = $oldPass;
				$newPas = false;
			}
			
			if($model->validate()) {
				if($newPas)
					$model->password = md5($model->password);
				
				if($model->save(false)) {
					Yii::app()->user->setFlash('success', 'Данные успешно сохранены');
					$model->_password2 = $model->password = '';
				}
			}
		}
		
		$this->render('profile', array('model'=>$model));		
	}
	
	public function actionNewpas() {
		$model = new NewpasForm;
		
		if(isset($_POST['NewpasForm'])) {
			$model->attributes = $_POST['NewpasForm'];
			if($model->validate()) {
				if($user = User::getByEmail($model->email)) {
					$user->sendNewPas();
					Yii::app()->user->setFlash('success', 'Новый пароль отправлен');
					$this->redirect('site/login');
				}
				$model->addError('email', 'Пользователь не найден');
			}
		}
		
		$this->render('newpas', array('model'=>$model));
	}
	
	
	public function actionStatistic() {
		
		$result = array('result'=>'Нет результата');
		if(isset($_POST['statistic_start_date'], $_POST['statistic_end_date'])) {
			$user = Yii::app()->user->getModel();
			$data = $user->getPLStatistic($_POST['statistic_start_date'], $_POST['statistic_end_date']);
			
			if($data)
				$result = array('result'=>$this->renderPartial('_statistic_period', array('data' => $data), true, false));
		}	
		echo CJSON::encode($result);
		Yii::app()->end();
	}
	
	
	/**
	 * user came by personal link
	 */
	public function actionPl() {
		if(isset($_GET['pk']) && ($user = User::getByPersonalKey($_GET['pk']))) {
			//save statistic 
			UserPLStatistic::saveStatistic($user->id, 'personal_link');
			
			// set cookies
			Yii::app()->request->cookies['pk'] = new CHttpCookie('pk', $_GET['pk']);
			$this->redirect('/user/registration');
		}	
	}
	
	/**
	 * user came from mail
	 */
	public function actionMlr() {
		
		if(isset($_GET['pk'])) {
			$a = User::parsePersonalLink($_GET['pk']);
			
			if(($user = User::getByPersonalKey($a['pk'])) &&
			($statistic = UserMailerStatistic::getByIdAndUserId($a['id'], $user->id)))
			{
				//save statistic 
				UserPLStatistic::saveStatistic($user->id, 'mailer');
				$user->updateBalance(1);
				
				// set cookies
				Yii::app()->request->cookies['mlr'] = new CHttpCookie('mlr', $a['pk']);
				
				$model = new User;
				$model->setScenario('registration');
				$model->email = $statistic->email;
				$model->first_name = $statistic->first_name;
				$model->last_name = $statistic->last_name;
				
				$this->render('/deal/index', array('newUser'=>$model));	
			}
		}	
	}
	
	public function actionFk() {
		
		if(isset($_GET['pk']) && ($user = User::getByPersonalKey($_GET['pk']))) {
			
			$model = new User;
			$model->setScenario('registration');
			
			$this->render('/deal/index', array('punishedUser'=>$user, 'model'=>$model));	
		}	
	}

	
	public function actionRecommend() {
		$this->render('recommend');	
	}
	
	public function actionSendEmails() {
		if($_POST['emails']) {
			$user = Yii::app()->user->getModel();
			
			$emails = $_POST['emails'];
			$firstName = $_POST['first_name'];
			$lastName = $_POST['last_name'];
			$succes = $error = '';
			$c = count($emails);
			
			$validator = new MailerValidator;
			
			for($i=0; $i<$c; $i++) {
				if($emails[$i]) {
					$result = $validator->validate($emails[$i]);
					if($result == '') {
						$user->sendToFriend($emails[$i], $firstName[$i], $lastName[$i]);
						$user->updateBalance(1);
						$succes .= $emails[$i] .' - пиьсмо успешно отправленно<br />';	
					} else
					    $error .= $result;
				}
			}
			
			// display results
			if($succes)
				Yii::app()->user->setFlash('success', $succes);
			if($error)
				Yii::app()->user->setFlash('error', $error);
				
		}
		$this->redirect('/user/profile');	
	}
	
	/**
	 * 
	 */
	public function actionPunished() {
		if(isset($_POST['u']) && ($user = User::getByPersonalKey($_POST['u'])))	{
			if($user->updateComplaint(1)) {
				UserPunishedStatistic::updateStatistic($user->id);
				echo $user->first_name .' '. $user->last_name . ' был наказан';
				Yii::app()->end();
			}	
		}
	} 
}